import { Component, Vue, Watch } from 'vue-property-decorator'
import styles from './administratorApply.less'
import service from '@/lib/service'
import SelectTree from '../../components/SelectTree'
import SelectTreeEmpty from '../../modules/selectTreeEmpty'
import Upload from '@/components/Upload'
import PrintDialog from '../ApplyPage/PrintDialog'
import { Action, State } from 'vuex-class'
import { RootState } from '@/store'
import { ElForm } from 'element-ui/types/form'
import ImagePreview from '@/components/ImagePreview'
import { UserState } from '@/store/modules/user'
import { formatStatus } from '@/lib/sealFormat'
import {
  IStatus,
  userLicenseTypes,
  orgTypes,
  orgLicenseTypes,
} from '@/lib/sealFormat'
const fileTypes = [
  'image/jpeg',
  'image/jpg',
  'image/png',
  'image/bmp',
  'image/gif',
]
const fileSizeLimit = 10
const formRule = {
  applyOrganizeName: [
    {
      required: true,
      message: '请输入授权机构名称进行搜索',
      trigger: ['input', 'change'],
    },
  ],
  orgName: [
    {
      required: true,
      message: '机构单位名称不能为空',
      trigger: 'change',
    },
  ],
  applyOrganizeLicenseNumber: [
    {
      required: true,
      message: '证照号码不能为空',
      trigger: 'change',
    },
    {
      len: 18,
      message: '长度没有达到 18 位',
      trigger: 'change',
    },
  ],
  applyName: [{ required: true, message: '申请人姓名为空', trigger: 'change' }],
  applyMobile: [
    { required: true, message: '申请人手机号为空', trigger: 'change' },
  ],
  applyLicenseType: [
    { required: true, message: '申请人证件类型为空', trigger: 'change' },
  ],
  applyLicenseNumber: [
    { required: true, message: '申请人证件号为空', trigger: 'change' },
  ],
}

@Component({})
export default class OrganizationApply extends Vue {
  @Action('applyPage/getInitTree') private getInitTree!: any
  @State((state: RootState) => state.user) private user!: UserState

  private formData: any = {
    area: [],
    applyOrganizeUuid: '',
    applyOrganizeName: '',
    applyOrganizeLicenseType: 1,
    applyOrganizeLicenseNumber: '',
    applyFileKey: '',
    licenseFileUrl: '',
    applyLicenseNumber: '',
    applyLicenseType: '',
    applyMobile: '',
    applyName: '',
    applyOrganizeType: 50,
    applyType: 7,
  }
  private loadTree = false
  private defaultExpended: any = []
  private areaData: any[] = []
  private uploadUrl: string = '/seal/rest/file/uploadPicMulti'
  private file: any = {
    status: 'init',
  }

  private active: number = 0
  private imgVisible = false

  private sealApplyOpsBOs = []

  private printVisible: boolean = false

  private name: string = ''

  private fileProgress(event: any, file: any, fileList: any[]) {
    this.file = Object.assign(
      {},
      {
        name: file.name,
        status: 'upload',
        size: file.size,
        precent: parseInt(file.percentage),
      }
    )
  }

  private uploadSuccess(response: any, file: any, fileList: any[]) {
    if (response.errCode === 0) {
      this.file = Object.assign(
        {},
        {
          name: file.name,
          status: 'done',
          size: file.size,
          url: URL.createObjectURL(file.raw),
        }
      )
      this.formData.applyFileKey = response.data.fileKey
      this.formData.licenseFileUrl = response.data.fileUrl
    }
  }

  private uploadError(err: any, file: any, fileList: any[]) {
    this.file = {}
    this.formData.licenseNumberFileKey = ''
    this.$message.error('文件上传失败')
  }

  private beforeUpload(file: any) {
    const isJPG =
      fileTypes.filter(
        (item: string) => item === (file.type || '').toLowerCase()
      ).length > 0
    const isLimit = file.size / 1024 / 1024 < fileSizeLimit
    if (!isJPG) {
      this.$message.error('申请表只能是 JPG/PNG/BMP/JPEG 格式。')

      return false
    }
    if (!isLimit) {
      this.$message.error(`申请表大小不能超过${fileSizeLimit}MB。`)

      return false
    }
    this.file = Object.assign(
      {},
      { name: file.name, status: 'upload', size: file.size, precent: 0 }
    )
  }

  protected render() {
    return (
      <div class={styles.administratorApply}>
        <div>
          <el-steps active={this.active} align-center>
            <el-step title="选择授权范围" />
            <el-step title="机构印章管理员申请表" />
            <el-step title="完成" />
          </el-steps>
          <div>
            {this.active === 0 && (
              <el-form
                size="mini"
                ref="form"
                {...{
                  props: { model: this.formData, rules: formRule },
                }}
              >
                <div>
                  <h1>
                    <i>*</i>申请授权机构范围
                  </h1>
                  <el-form-item label="授权机构所属区域" prop="area">
                    <el-cascader
                      v-model={this.formData.area}
                      options={this.areaData}
                      show-all-levels={false}
                      {...{
                        props: {
                          props: {
                            value: 'uuid',
                            label: 'fullName',
                            children: 'subList',
                          },
                        },
                      }}
                    />
                  </el-form-item>
                  <el-form-item label="授权机构名称" prop="applyOrganizeName">
                    <SelectTree
                      ref="selectTree"
                      class="query-select"
                      loading={this.loadTree}
                      parentId={this.formData.area.slice(-1)[0]}
                      value={this.formData.applyOrganizeName}
                      onInit={this.getAllTree}
                      defaultExpended={this.defaultExpended}
                      onHandleNodeClick={this.selectOrg}
                      onInput={this.inputSelectTree}
                    >
                      <template slot="empty">
                        <SelectTreeEmpty />
                      </template>
                    </SelectTree>
                  </el-form-item>
                  <el-form-item label="机构类型">
                    <el-select
                      v-model={this.formData.applyOrganizeType}
                      autocomplete="off"
                      disabled
                      placeholder=""
                    >
                      {orgTypes.map((orgType: IStatus, index: number) => (
                        <el-option label={orgType.value} value={orgType.id} />
                      ))}
                    </el-select>

                    {/* <el-input disabled value="单位"></el-input> */}
                  </el-form-item>
                  <el-form-item label="证照类型">
                    {/* <el-input disabled value="统一社会信用代码"></el-input> */}
                    <el-select
                      v-model={this.formData.applyOrganizeLicenseType}
                      disabled
                      placeholder=""
                    >
                      {orgLicenseTypes.map(
                        (orgType: IStatus, index: number) => (
                          <el-option label={orgType.value} value={orgType.id} />
                        )
                      )}
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="证照号码"
                    prop="applyOrganizeLicenseNumber"
                  >
                    <el-input
                      disabled
                      maxlength={18}
                      v-model={this.formData.applyOrganizeLicenseNumber}
                    />
                  </el-form-item>

                  <h1 class="upload-header">
                    <i>*</i>申请人基本信息
                  </h1>
                  <el-form-item label="申请人姓名" prop="applyName">
                    <el-input v-model={this.formData.applyName} disabled />
                  </el-form-item>
                  <el-form-item label="申请人手机号码" prop="applyMobile">
                    <el-input v-model={this.formData.applyMobile} disabled />
                  </el-form-item>
                  <el-form-item label="申请人证件类型" prop="applyLicenseType">
                    <el-select
                      v-model={this.formData.applyLicenseType}
                      disabled
                      placeholder=""
                    >
                      {userLicenseTypes.map(
                        (orgType: IStatus, index: number) => (
                          <el-option label={orgType.value} value={orgType.id} />
                        )
                      )}
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="申请人证件号码"
                    prop="applyLicenseNumber"
                  >
                    <el-input
                      v-model={this.formData.applyLicenseNumber}
                      disabled
                    />
                  </el-form-item>
                </div>
                <el-form-item class="footer">
                  <el-button onClick={() => this.$router.go(-1)}>
                    关闭
                  </el-button>
                  <el-button type="primary" onClick={() => this.next(0)}>
                    下一步
                  </el-button>
                </el-form-item>
              </el-form>
            )}
            {this.active === 1 && (
              <div class={styles.uploadWrapper}>
                <h1 class="upload-header">
                  <i>*</i>机构印章管理员申请表
                </h1>
                <div class={styles.splice}>
                  <el-button onClick={this.createApplyForm}>
                    <img src={require('@/assets/create-form.png')} />
                    生成并下载申请表
                  </el-button>
                </div>
                <div class={styles.uploadContent}>
                  <Upload
                    file={this.file}
                    progress={this.fileProgress}
                    action={this.uploadUrl}
                    success={this.uploadSuccess}
                    error={this.uploadError}
                    preview={this.preview}
                    content="上传机构印章管理员申请表"
                    beforeUpload={this.beforeUpload}
                  />
                  <div class="tips">
                    上传须知：
                    <br />
                    1、图片按照A4纸大小扫描，像素300dpi <br />
                    2、格式须为PNG/JPG/BMP/JPEG/GIF <br />
                    3、再次确认申请表中的签字、盖章等重要信息清晰可辨
                    <br />
                    4、申请表需要具有授权单位的盖章确认
                  </div>
                </div>
                <div>
                  <el-button onClick={() => this.goback(0)}>上一步</el-button>
                  <el-button onClick={() => this.save()}>暂不提交</el-button>
                  <el-button type="primary" onClick={() => this.submitEvt()}>
                    确认提交
                  </el-button>
                </div>
              </div>
            )}

            {this.active === 2 && (
              <div class={styles.successStep}>
                <i class="el-icon-circle-check" />
                <p>机构印章管理员申请已发起，请关注授权通知</p>
                <el-button onClick={() => this.$router.go(-1)}>返回</el-button>
              </div>
            )}
          </div>
        </div>
        {!!this.sealApplyOpsBOs.length && (
          <div>
            <h4>机构印章管理员申请信息</h4>
            <el-timeline>
              {this.sealApplyOpsBOs.map((activity: any, index: number) => (
                <el-timeline-item key={index} timestamp={activity.time}>
                  <div class={{ [styles.red]: activity.operatorType === 6 }}>
                    {activity.operatorTypeName}
                  </div>
                  <div>{activity.content}</div>
                </el-timeline-item>
              ))}
            </el-timeline>
          </div>
        )}
        <PrintDialog
          onVisibleChange={(val: boolean) => {
            this.printVisible = false
          }}
          visible={this.printVisible}
          printHtml={this.printHtml}
        />
        <ImagePreview
          visible={this.imgVisible}
          title="证明材料预览"
          url={this.file.url}
          onVisibleChange={(val: boolean) => {
            this.imgVisible = val
          }}
        />
      </div>
    )
  }

  @Watch('user.accountUUID')
  private userChange(val: string) {
    console.log(666)
    const { applyId } = this.$route.query
    if (!applyId) {
      this.formData.applyLicenseNumber = this.user.accountLicenseNumber
      this.formData.applyLicenseType = this.user.accountLicenseType
      this.formData.applyMobile = this.user.accountMobile
      this.formData.applyName = this.user.accountName
      this.formData.accountUUID = this.user.accountUUID
    }
  }

  private submitEvt() {
    if (!this.formData.applyFileKey) {
      this.$message.warning('请选择你要提交的图片')

      return
    }

    service({
      url: '/seal/rest/apply/submitManagerApply',
      method: 'POST',
      body: this.formData,
    }).then(res => {
      if (res.errCode === 0) {
        this.active = 2
      }
    })
  }

  private goback(active: number) {
    this.active = active
  }

  private save() {
    console.log('暂时保存', this.formData)
    service({
      url: '/seal/rest/apply/saveManagerApply',
      method: 'POST',
      body: this.formData,
    }).then(res => {
      if (res.errCode === 0) {
        this.$router.go(-1)
      }
    })
  }

  private next(active?: number) {
    if (active === 0) {
      const form = this.$refs.form as ElForm
      this.formData.applyOrganizeName = this.name
      form.validate(result => {
        if (result) {
          this.active = 1
        }
      })
    }
  }

  private mounted() {
    this.remoteAreaData()
    const { applyId } = this.$route.query
    if (applyId) {
      this.formData.applyId = applyId
      service({
        url: '/seal/rest/manager/queryManagerApplyDetail',
        method: 'POST',
        body: {
          applyId: applyId,
        },
      }).then(res => {
        if (res.errCode === 0) {
          this.name = res.data.applyOrganizeName
          this.formData.applyLicenseNumber = res.data.applyLicenseNumber
          this.formData.applyLicenseType = res.data.applyLicenseType
          this.formData.applyMobile = res.data.applyMobile
          this.formData.applyName = res.data.applyName
          this.formData.accountUUID = res.data.accountUUID
          this.formData.applyOrganizeName = res.data.applyOrganizeName
          this.formData.applyOrganizeUuid = res.data.applyOrganizeUuid
          this.formData.applyOrganizeType = res.data.applyOrganizeType
          this.formData.applyOrganizeLicenseNumber =
            res.data.applyOrganizeLicenseNumber
          this.formData.applyOrganizeLicenseType =
            res.data.applyOrganizeLicenseType
          this.file.url = res.data.applyPicUrl
          this.formData.applyFileKey = res.data.applyFileKey
          this.sealApplyOpsBOs = res.data.sealApplyOpsBOs
        }
      })
    } else {
      this.formData.applyLicenseNumber = this.user.accountLicenseNumber
      this.formData.applyLicenseType = this.user.accountLicenseType
      this.formData.applyMobile = this.user.accountMobile
      this.formData.applyName = this.user.accountName
      this.formData.accountUUID = this.user.accountUUID
    }
  }

  private setStatus(data: any[], ignore: boolean) {
    data.forEach((item: any) => {
      item.isLeaf = ignore ? true : !item.subFlag
      if (item.subList) {
        this.defaultExpended.push(item.uuid)
        this.setStatus(item.subList, ignore)
      }
    })
  }

  private getAllTree(data: {
    uuid: string
    resolve: any
    text: string
    isFirst: boolean
  }) {
    // 初始化树
    if (!this.formData.area) {
      this.$message.warning('请选择区域')

      return
    }

    this.defaultExpended = []
    this.loadTree = !!data.isFirst
    this.getInitTree({
      uuid: data.uuid || this.formData.area.slice(-1)[0],
      fullName: (data.text || '').trim(),
    })
      .then((res: any) => {
        this.loadTree = false
        const result = res.map((item: any) => {
          return {
            ...item,
            disabled: !item.selectable,
            isLeaf: !!(data.text || '').trim() ? true : item.subFlag === 0,
          }
        })
        this.setStatus(result, !!(data.text || '').trim())
        data.resolve(result)
      })
      .catch((e: any) => {
        this.loadTree = false
      })
  }

  private selectOrg(val: any) {
    this.formData.applyOrganizeName = ''
    this.$nextTick(() => {
      this.name = val.fullName
      this.formData.applyOrganizeName = val.fullName
      this.formData.applyOrganizeUuid = val.uuid
      this.formData.applyOrganizeType = val.organizeType
      this.formData.applyOrganizeLicenseNumber = val.licenseNumber
      this.formData.applyOrganizeLicenseType = val.licenseType
      ;(this.$refs.formData as ElForm) &&
        (this.$refs.formData as ElForm).clearValidate()
    })
  }

  private inputSelectTree(val: string) {
    this.formData.applyOrganizeName = val
    this.$nextTick(() => {
      ;(this.$refs.formData as ElForm) &&
        (this.$refs.formData as ElForm).clearValidate()
    })
  }

  private remoteAreaData() {
    service({
      url: '/seal/rest/organize/getArea',
      method: 'POST',
    }).then(res => {
      if (res.errCode === 0) {
        this.areaData = res.data
      }
    })
  }

  private preview() {
    this.imgVisible = true
  }

  private createApplyForm() {
    console.log(orgTypes, 'orgTypes')
    sessionStorage.setItem(
      'adminInfo',
      JSON.stringify({
        organize: this.formData.applyOrganizeName,
        orgType: formatStatus(orgTypes, this.formData.applyOrganizeType),
        licenseType: formatStatus(
          orgLicenseTypes,
          this.formData.applyOrganizeLicenseType
        ),
        licenseNumber: this.formData.applyOrganizeLicenseNumber,
        agentName: this.formData.applyName,
        agentLicenseType: formatStatus(
          userLicenseTypes,
          this.formData.applyLicenseType
        ),
        agentLicenseNumber: this.formData.applyLicenseNumber,
        agentMobile: this.formData.applyMobile,
      })
    )
    this.printVisible = true
  }

  get printHtml() {
    return `${window.origin || window.location.origin}/adminApply`
  }
}
